package club.jdiy.admin.util;
import club.jdiy.core.ex.JDiyException;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;

/**
 * 
 * @ClassName：EncodeUtils   
 * @Description：密码加密   
 * @author：Any
 * @date：2015年3月24日 下午4:53:59      
 * @version
 */

public class EncodeUtil {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	public static final int SALT_SIZE = 8;

	public static String encode(String value, String encoding) {
		if (StringUtils.isBlank(value) || StringUtils.isBlank(encoding)) return null;
		String string = null;
		try {
			if (StringUtils.isNotBlank(value))
				string = new String(java.net.URLEncoder.encode(value, encoding));
		} catch (Exception ioe) {
			ioe.printStackTrace();
		}
		return string;
	}

	public static String decode(String value, String encoding) {
		if (StringUtils.isBlank(value) || StringUtils.isBlank(encoding))
			return null;
		String result = null;
		try {
			// 解码，然后将字节转换为文件
			// byte[] bytes = new BASE64Decoder().decodeBuffer(value);
			result = java.net.URLDecoder.decode(new String(value), encoding);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}


	/**
	 * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
	 */
	public static String entryptPassword(String plainPassword) {
		byte[] salt = generateSalt(SALT_SIZE);
		byte[] hashPassword = sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
		return EncodeUtil.encodeHex(salt) + EncodeUtil.encodeHex(hashPassword);
	}

	/**
	 * 验证密码
	 * @param plainPassword 明文密码
	 * @param password 密文密码
	 * @return 验证成功返回true
	 */
	public static boolean validatePassword(String plainPassword, String password) {
		byte[] salt = EncodeUtil.decodeHex(password.substring(0, 16));
		byte[] hashPassword = sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
		return password.equals(EncodeUtil.encodeHex(salt) + EncodeUtil.encodeHex(hashPassword));
	}


	/**
	 * Hex编码.
	 */
	public static String encodeHex(byte[] input) {
		return Hex.encodeHexString(input);
	}

	/**
	 * Hex解码.
	 */
	public static byte[] decodeHex(String input) {
		try {
			return Hex.decodeHex(input.toCharArray());
		} catch (DecoderException e) {
			JDiyException le = new JDiyException(e.getMessage());
			le.setStackTrace(e.getStackTrace());
			throw le;
		}
	}

	public static void main(String[] args) {

		String aa = EncodeUtil.entryptPassword("YY4295811");
		System.out.println(aa);
		System.out.println(EncodeUtil.validatePassword("YY4295811", "1ea4633d57a56c74d700bb458701e278555bf57077fc1ab4981d38a7"));
		//System.out.println(EncodeUtil.entryptPassword("123456"));

	}



	private static SecureRandom random = new SecureRandom();

	public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");

			if (salt != null) {
				digest.update(salt);
			}

			byte[] result = digest.digest(input);

			for (int i = 1; i < iterations; i++) {
				digest.reset();
				result = digest.digest(result);
			}
			return result;
		} catch (GeneralSecurityException e) {
			JDiyException le = new JDiyException(e.getMessage());
			le.setStackTrace(e.getStackTrace());
			throw le;
		}
	}


	/**
	 * 生成随机的Byte[]作为salt.
	 *
	 * @param numBytes byte数组的大小
	 */
	public static byte[] generateSalt(int numBytes) {
		Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);

		byte[] bytes = new byte[numBytes];
		random.nextBytes(bytes);
		return bytes;
	}
}
